//初始化编辑器
window.UEDITOR_CONFIG = {
    // 为编辑器实例添加一个路径，这个不能被注释
    UEDITOR_HOME_URL: basePath+"js/ueditor/",
    // 服务器统一请求接口路径
    serverUrl:basePath+ "ueditor/dispatch"
};

var uEditorFormat = {
    initialFrameHeight: 200,//编辑区域高度
    maximumWords: 30000,
    autoHeightEnabled: false,
    autoFloatEnabled: true,
    allowDivTransToP: false,
    toolbars: [[
        'preview', //预览
        'source', //源代码
        'bold', //加粗
        'indent', //首行缩进
        'italic', //斜体meta
        'underline', //下划线
        'strikethrough', //删除线
        'subscript', //下标
        'fontborder', //字符边框
        'superscript', //上标
        'formatmatch', //格式刷
        'blockquote', //引用
        'pasteplain', //纯文本粘贴模式
        'horizontal', //分隔线
        'removeformat', //清除格式
        'time', //时间
        'date', //日期
        'link',
        'unlink', //取消链接
        'inserttitle', //插入标题
        // 'insertcode', //代码语言
        'fontfamily', //字体
        'fontsize', //字号
        // 'paragraph', //段落格式
        // 'emotion', //表情
        'spechars', //特殊字符
        'simpleupload', //单图上传
        'justifyleft', //居左对齐
        'justifyright', //居右对齐
        'justifycenter', //居中对齐
        'justifyjustify', //两端对齐
        'forecolor', //字体颜色
        'backcolor', //背景色
        // 'insertorderedlist', //有序列表
        // 'insertunorderedlist', //无序列表
        // 'directionalityltr', //从左向右输入
        // 'directionalityrtl', //从右向左输入
        'rowspacingtop', //段前距
        'rowspacingbottom', //段后距
        'imagenone', //默认
        'imageleft', //左浮动
        'imageright', //右浮动
        'imagecenter', //居中
        'lineheight', //行间距
        'edittip ', //编辑提示
        'customstyle', //自定义标题
        'autotypeset', //自动排版
        // 'help', //帮助
        'cleardoc' //清空文档
    ]]
}

var ueMapList = new Array();
var defPackageNum = 0;
var defPackageCount = 1;
var isChange = false;

$(function () {
    if (hasPackage == 1) {
        initPackageDiv();
    }
    if (editType != 'info') {
        regValidate(["#_orgBizAppDataForm"]);
    }
});

function initPackageDiv() {
    if (!packageList || packageList.length == 0) {
        return;
    }
    var strHtml = '';
    for (var i=0; i<packageList.length; i++) {
        (function(i){
            var pack = packageList[i];
            strHtml = getPackageInfoHtml(pack);
            $('#_packageDiv').append(strHtml);
            var id = 'packageContent' + defPackageCount;
            var ue = UE.getEditor(id, uEditorFormat);
            console.log(111);
            ue.ready(function() {
                console.log(222);
                ue.setContent(pack.packageContent ? pack.packageContent : '');
            });
            console.log(333);
            var ueMap = {
                flag : defPackageCount,
                uEditor : ue
            };
            ueMapList.push(ueMap);
            defPackageNum++;
            defPackageCount++;
        })(i);
    }
}

function getPackageInfoHtml(packageInfo) {
    var strHtml = '<div class="form-group" id="_'+ defPackageCount +'">\n' +
        '                                                        <label class="col-sm-1 center-text">\n' +
        '                                                            <input type="checkbox" name="check-package" value="'+ defPackageCount +'"/>\n' +
        '                                                        </label>\n' +
        '                                                        <div class="col-sm-10 div-style">\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>服务包名称：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <input type="hidden" value="'+ packageInfo.packageCode +'"' +
        '                                                                    id="packageCode'+ defPackageCount +'" name="packageCode'+ defPackageCount +'">\n';
    if (packageInfo.bizPackageCode == '-1') {
        strHtml += '<input type="text" class="form-control" id="packageNameSelf'+ defPackageCount +'" name="packageName'+ defPackageCount +'" maxlength="50" required value="'+ packageInfo.packageName +'">';
    } else {
        strHtml += '<select class="form-control" name="packageName'+ defPackageCount +'" id="packageName'+ defPackageCount +'" required>\n' +
            getPackageCodeOption(packageInfo.bizPackageCode) + '</select>\n';
    }
    strHtml += '<span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>排序：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <input type="text" value="'+ packageInfo.sortNum +'" ' +
        '                                                                     id="sortNum'+ defPackageCount +'" name="sortNum'+ defPackageCount +'" class="form-control" maxlength="9" digits="true" required>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>简介：</label>\n' +
        '                                                                <div class="col-sm-8">\n' +
        '                                                                    <input type="text" value="'+ packageInfo.summary +'"' +
        '                                                                     id="summary'+ defPackageCount +'" name="summary'+ defPackageCount +'" class="form-control" maxlength="500" required>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>服务说明：</label>\n' +
        '                                                                <div class="col-sm-8">\n' +
        '                                                                    <script id="packageContent'+ defPackageCount +'" name="packageContent" type="text/html"></script>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label" required><span style="color: red">*</span>是否必备：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <select class="form-control" name="isRequired" id="isRequired'+ defPackageCount +'" required>\n' +
        getPackageIsRequiredOption(packageInfo.isRequired) +
        '                                                                    </select>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                        </div>\n' +
        '                                                    </div>';
    return strHtml;
}

function doAddPackageSelf() {
    isChange = true;
    if (defPackageNum >= 10) {
        toastr.error('服务包数量不能大于10个');
        return;
    }
    var strHtml = '<div class="form-group" id="_'+ defPackageCount +'">\n' +
        '                                                        <label class="col-sm-1 center-text">\n' +
        '                                                            <input type="checkbox" name="check-package" value="'+ defPackageCount +'"/>\n' +
        '                                                        </label>\n' +
        '                                                        <div class="col-sm-10 div-style">\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>服务包名称：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <input type="hidden" id="packageCode'+ defPackageCount +'" name="packageCode'+ defPackageCount +'">\n' +
        '                                                                    <input type="text" class="form-control" id="packageNameSelf'+ defPackageCount +'" name="packageName'+ defPackageCount +'" maxlength="50" required>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>排序：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <input type="text" id="sortNum'+ defPackageCount +'" name="sortNum'+ defPackageCount +'" class="form-control" maxlength="9" digits="true" required>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>简介：</label>\n' +
        '                                                                <div class="col-sm-8">\n' +
        '                                                                    <input type="text" id="summary'+ defPackageCount +'" name="summary'+ defPackageCount +'" class="form-control" maxlength="500" required>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>服务说明：</label>\n' +
        '                                                                <div class="col-sm-8">\n' +
        '                                                                    <script id="packageContent'+ defPackageCount +'" name="packageContent" type="text/html"></script>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label" required><span style="color: red">*</span>是否必备：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <select class="form-control" name="isRequired" id="isRequired'+ defPackageCount +'" required>\n' +
        '                                                                        <option value="N">否</option>\n' +
        '                                                                        <option value="Y">是</option>\n' +
        '                                                                    </select>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                        </div>\n' +
        '                                                    </div>';
    var id = 'packageContent' + defPackageCount;
    $('#_packageDiv').append(strHtml);
    var ue = UE.getEditor(id, uEditorFormat);
    var ueMap = {
        flag : defPackageCount,
        uEditor : ue
    };
    ueMapList.push(ueMap);
    defPackageNum++;
    defPackageCount++;
    if (editType != 'info') {
        regValidate(["#_orgBizAppDataForm"]);
    }
}

function doAddPackage() {
    isChange = true;
    if (defPackageNum >= 10) {
        toastr.error('服务包数量不能大于10个');
        return;
    }
    var strHtml = '<div class="form-group" id="_'+ defPackageCount +'">\n' +
        '                                                        <label class="col-sm-1 center-text">\n' +
        '                                                            <input type="checkbox" name="check-package" value="'+ defPackageCount +'"/>\n' +
        '                                                        </label>\n' +
        '                                                        <div class="col-sm-10 div-style">\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>服务包名称：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <input type="hidden" id="packageCode'+ defPackageCount +'" name="packageCode'+ defPackageCount +'">\n' +
        '                                                                    <select class="form-control" name="packageName'+ defPackageCount +'" id="packageName'+ defPackageCount +'" required>\n' +
        getPackageCodeOption() +
        '                                                                    </select>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>排序：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <input type="text" id="sortNum'+ defPackageCount +'" name="sortNum'+ defPackageCount +'" class="form-control" maxlength="9" digits="true" required>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>简介：</label>\n' +
        '                                                                <div class="col-sm-8">\n' +
        '                                                                    <input type="text" id="summary'+ defPackageCount +'" name="summary'+ defPackageCount +'" class="form-control" maxlength="500" required>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label"><span style="color: red">*</span>服务说明：</label>\n' +
        '                                                                <div class="col-sm-8">\n' +
        '                                                                    <script id="packageContent'+ defPackageCount +'" name="packageContent" type="text/html"></script>\n' +
        '                                                                    <span class="help-block m-b-none tip"></span>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="form-group form-group-new">\n' +
        '                                                                <label class="col-sm-2 control-label" required><span style="color: red">*</span>是否必备：</label>\n' +
        '                                                                <div class="col-sm-3">\n' +
        '                                                                    <select class="form-control" name="isRequired" id="isRequired'+ defPackageCount +'" required>\n' +
        '                                                                        <option value="N">否</option>\n' +
        '                                                                        <option value="Y">是</option>\n' +
        '                                                                    </select>\n' +
        '                                                                </div>\n' +
        '                                                            </div>\n' +
        '                                                        </div>\n' +
        '                                                    </div>';
    var id = 'packageContent' + defPackageCount;
    $('#_packageDiv').append(strHtml);
    var ue = UE.getEditor(id, uEditorFormat);
    var ueMap = {
        flag : defPackageCount,
        uEditor : ue
    };
    ueMapList.push(ueMap);
    defPackageNum++;
    defPackageCount++;
    if (editType != 'info') {
        regValidate(["#_orgBizAppDataForm"]);
    }
}

function getPackageCodeOption(bizPackageCode) {
    var str = '<option value="">--请选择--</option>';
    if (packageMap && packageMap.length != 0) {
        for (var i=0; i<packageMap.length; i++) {
            str += '<option value="'+ packageMap[i].code +'" '
            if (bizPackageCode == packageMap[i].code) {
                str += ' selected '
            }
            str += ' >'+ packageMap[i].name +'</option>';
        }
    }
    return str;
}

function getPackageIsRequiredOption(isRequired) {
    var str1 = '<option value="Y"';
    if (isRequired == 'Y') {
        str1 += ' selected ';
    }
    str1 += '>是</option>';
    var str2 = '<option value="N"';
    if (isRequired == 'N') {
        str2 += ' selected ';
    }
    str2 += '>否</option>';
    return str2 + str1;
}

function doDelPackage() {
    isChange = true;
    var checks = $('input[name="check-package"]:checked');
    if (!checks || checks.length == 0) {
        toastr.error('请先选择服务包再删除');
        return;
    }
    var strHtml = '确认删除服务包吗？';
    swalToastr('', strHtml, 'warning', delPackage);
}

function delPackage() {
    var checks = $('input[name="check-package"]:checked');
    checks.each(function(idx,element){
        var val = $(element).val();
        var id = '_' + val;
        $('#' + id).remove();
        defPackageNum--;
        for (var i=0; i<ueMapList.length; i++) {
            if (ueMapList[i].flag == val) {
                ueMapList.splice(i, 1);
                break;
            }
        }
    });
}

function doOrgBizAppSave() {
    if(!$("#_orgBizAppDataForm").valid()) return;//校验不通过
    var status = $('#status').val();
    var validDay = $('#validDay').val();
    var sortNum = $('#sortNum').val();
    sortNum = sortNum ? sortNum: 999
    var postData = {
        status : status,
        validDay : validDay,
        sortNum : sortNum,
        appid : oneBizAppInfo.appid,
        orgCode : oneBizAppInfo.refCode,
        bizCode : oneBizAppInfo.bizCode,
    }
    if (oneBizAppInfo.appType == 'html') {
        postData.appLinkUrl = $('#appLinkUrl').val();
    }
    if (hasPackage == 1) {
        var checks = $('input[name="check-package"]');
        if (checks && checks.length > 0) {
            var packageList = [];
            checks.each(function(idx,element){
                var val = $(element).val();
                var id1 = 'packageName' + val;
                var id2 = 'sortNum' + val;
                var id3 = 'summary' + val;
                var id4 = 'isRequired' + val;
                var id5 = 'packageCode' + val;
                var id6 = 'packageNameSelf' + val;
                var packageName = '', bizPackageCode = '';
                if ($('#' + id6).val()) {
                    packageName = $('#' + id6).val();
                    bizPackageCode = '-1';
                } else {
                    packageName = $('#' + id1).find("option:selected").text();
                    bizPackageCode = $('#' + id1).val();
                }
                var info = {
                    bizPackageCode : bizPackageCode,
                    packageName : packageName,
                    sortNum : $('#' + id2).val() ? $('#' + id2).val() : 999,
                    summary : $('#' + id3).val(),
                    isRequired : $('#' + id4).val(),
                    packageCode : $('#' + id5).val(),
                };
                for (var i=0; i<ueMapList.length; i++) {
                    if (ueMapList[i].flag == val) {
                        info.packageContent = ueMapList[i].uEditor.getContent();
                        break;
                    }
                }
                packageList.push(info);
            });
            for (var i=0; i<packageList.length; i++) {
                for (var j=i+1; j<packageList.length; j++) {
                    if (packageList[j].packageName == packageList[i].packageName) {
                        toastr.error('服务包不能重复添加，请重新选择');
                        return;
                    }
                }
            }
            postData.packageList = packageList;
        }
    }
    postData.id = oneBizAppInfo.id;
    url = basePath + 'bizApp/editOrgChildBizApp?t=' + new Date().getTime();
    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        data: postData,
        success : function (data) {
            if(data && data.isSuccess){
                doBack();
            }else if(data&&!data.isSuccess){
                toastr.error(data.errorDesc);
            }else{
                toastr.error(common_save_fail);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function doCheckDataChange() {
    var data = getFromData('#_orgBizAppDataForm');
    var checkData = {
        status : data.status,
        validDay : data.validDay,
        sortNum : data.sortNum,
    };
    if (oneBizAppInfo.otherServiceType == 'html') {
        checkData.appLinkUrl = data.appLinkUrl;
    }
    if (editType != 'info' && (!Compare(checkData, oneBizAppInfo) || isChange)) {
        swalClosePageToastr(doBack);
        return;
    }
    doBack();
}

function doBack() {
    var str = '&cBizName=' + searchInfo.cBizName +
        '&cStatus=' + searchInfo.cStatus +
        '&cOrgName=' + searchInfo.cOrgName +
        '&cPageSize1=' + searchInfo.cPageSize1 +
        '&cPageNo1=' + searchInfo.cPageNo1 +
        '&cPageSize2=' + searchInfo.cPageSize2 +
        '&cPageNo2=' + searchInfo.cPageNo2 +
        '&pAppId=' + searchInfo.pAppId +
        '&pIsvPid=' + searchInfo.pIsvPid +
        '&pRefCode=' + searchInfo.pRefCode +
        '&pBizCode=' + searchInfo.pBizCode +
        '&pIsvName=' + searchInfo.pIsvName +
        '&pOrgName=' + searchInfo.pOrgName +
        '&pBizName=' + searchInfo.pBizName +
        '&isTeamExist=' + searchInfo.isTeamExist +
        '&isDocExist=' + searchInfo.isDocExist +
        '&orgName=' + searchInfo.orgName +
        '&bizCode=' + searchInfo.bizCode +
        '&status=' + searchInfo.status +
        '&dataStatus=' + searchInfo.dataStatus +
        '&isvPid=' + searchInfo.isvPid +
        '&searchStr=' + searchStr +
        '&isvName=' + searchInfo.isvName;
    window.location.href = basePath + 'bizApp/bizAppChildrenBiz?t=' + new Date().getTime() + str;
}